import random
import time

from django.http import HttpResponse, JsonResponse
from django.views import View
from libs.rl_sms import send_message
from libs.captcha.captcha import captcha
from redis import StrictRedis


# 图形验证码
class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request:     请求对象
        :param uuid:        唯一标识图形验证码所属于的用户
        :return:            image/jpg
        """
        # 生成图片及答案
        text, image = captcha.generate_captcha()

        # 保存答案和 uuid 到 redis 中
        client = StrictRedis()  # 默认连接到 127.0.0.1 的 6379 端口
        client.set(uuid, text)

        return HttpResponse(image, content_type='image/jpeg')
        pass


# 发送短信验证
class SMSCodeView(View):
    """短信验证码"""

    def get(self, request, mobile):
        # 接收参数
        image_code = request.GET.get("image_code")
        uuid = request.GET.get("uuid")
        # 校验参数
        if not all([mobile, image_code, uuid]):
            return JsonResponse({"code": 999, "msg": "缺少参数"})
        # 判断图形验证码
        # 1、从 redis 取
        client = StrictRedis()
        redis_image_code = client.get(uuid)
        # 2从 redis 中删除
        client.delete(uuid)
        # 3、对比
        if redis_image_code:
            redis_image_code = redis_image_code.decode()
        else:
            redis_image_code = None
        if image_code.upper() == redis_image_code:
            pass
        else:
            return JsonResponse({"code": 999, "msg": "图形验证码不正确"})

        # 生成短信验证码
        sms_code = '%04d' % random.randint(0, 9999)

        # 把短信存到 redis 中
        client.setex(mobile, 5 * 60, sms_code)

        # 发送短信验证码
        import sys
        import os
        from meiduo.settings import BASE_DIR
        sys.path.insert(0, os.path.join(BASE_DIR, '../celery_task/'))
        from main import send_sms_code
        send_sms_code.delay(mobile, sms_code, '5')

        time.sleep(5)     # 用来倒计时延迟
        send_message(mobile, sms_code, '5')

        return JsonResponse({"code": 0, "msg": "ok"})
